package oop.core.control;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import oop.core.view.ControllerConfigMenu;

public class ControlConfigLoader {

	public void loadConfig(ControllerConfigMenu menu)
	{
		JFileChooser jFileChooser = new JFileChooser();
		jFileChooser.showOpenDialog(null);
		File file = jFileChooser.getSelectedFile();
		
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(file));
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(null, "Error opening the file.");
		}
		
		Map<Character, Integer> config = new HashMap<Character, Integer>();
		String line;
		try {
			while((line = br.readLine()) != null)
			{
				String[] parts = line.split("#");
				char c = parts[0].toCharArray()[0];
				int i = Integer.parseInt(parts[1]);
				config.put(c, i);
			}
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Error while loading the configuration file.");
		}
		
		menu.setConfig(config);
		if(!menu.isValidConfig())
		{
			JOptionPane.showMessageDialog(null, "Config file was invalid.");
			menu.resetMenu();
		}
		else
		{
			JOptionPane.showMessageDialog(null, "Load successful!");
		}
	}
}
